/**
 * ###### Install opengauss nodejs driver:
 * npm install node-opengauss --save
 * 
 * ###### Install babel deps:
 * npm install --save babel-core
 * npm install --save babel-preset-env 
 * npm install babel-cli -g
 * 
 * ###### Run:
 * babel-node index.js
 */

/**
 * 测试结论:
 * 
 * 测试点：
 *      基本的增删改查
 *      参数化执行
 * 
 * 
 * 发现问题：
 *      封装的OpenGauss接口不支持参数化执行   https://github.com/lolimay/node-opengauss/issues/8
 * 
 * 
 */

import OpenGauss from 'node-opengauss'

import sqlStrList from './dbopt/sql.js'
import sqlParamsList from './dbopt/sqlwithparam.js'

const client = new OpenGauss()
const config = {
    host: '192.168.0.4',
    port: 23400,
    username: 'test',
    database: 'testdb',
    password: 'xxxx'
}
console.log("start to connect to opengauss...");
client.connect(config);

function executerPromise(sql, params) {
    return new Promise((resolve, rejects) => {
        client.query_withparam(sql, params, (err, res) => {
            if (err) {
                rejects(err)
            }
            resolve(res);
        })
    })
}
var executer = async (sqlstr, params) => {
    // 同步创建连接
    try {
        // 同步等待结果
        var res = await executerPromise(sqlstr, params);
        // console.log(res)
        return res;
    } catch(e) {
        console.log(e)
    }
}

// 普通语句测试
excuter_sqlstr()

async function excuter_sqlstr(){
    for(let index in sqlStrList){
        let sqlstr = sqlStrList[index]
        console.log(sqlstr);
        let ret = await executer(sqlstr);
        console.log(ret);
    }
}

// 参数化语句测试
excuter_sqlParams()

async function excuter_sqlParams(){
    for(let index in sqlParamsList){
        let sqllist = sqlParamsList[index]
        if(sqllist.length == 2){
            executer(sqllist[0], sqllist[1]);
        }else{
            executer(sqllist[0]);
        }
    }
}

